package com.iceclean.daoImpl;

import com.iceclean.dao.PostDao;
import com.iceclean.po.Post;
import com.iceclean.po.PostBar;
import com.iceclean.util.JdbcUtil;

import java.util.List;

/**
 * @author : Ice'Clean
 * @date : 2021-05-04
 *
 * 贴子表操作实现类
 */
public class PostDaoImpl implements PostDao {

    @Override
    public Post findPostById(int postId) {
        List<Post> posts = JdbcUtil.query("select * from t_post where post_id = ?", Post.class, postId);
        return posts.size() == 0 ? null : posts.get(0);
    }

    @Override
    public List<Post> findPostsByPage(int postBarId, int page, int num, int postDelete, String sortClass, String sortWay) {
        List<Post> posts = JdbcUtil.query("select * from t_post where post_bar_id = ? and post_delete = ? order by "+ sortClass + " " + sortWay +" limit " + (page-1)*num + "," + num, Post.class, postBarId, postDelete);
        return posts.size() == 0 ? null : posts;
    }

    @Override
    public List<Post> findUserPostsByPage(int userId, int page, int num) {
        List<Post> posts = JdbcUtil.query("select * from t_post where user_id = ? and post_delete = 0 limit " + (page-1)*num + "," + num, Post.class, userId);
        return posts.size() == 0 ? null : posts;
    }

    /**
     * 对多个字段进行模糊搜索
     * 分别为：贴子标题和贴子内容
     * @param postBarId 贴吧 id
     * @param search 搜索字段
     * @param page 页数
     * @param num 每页的数目
     * @return 符合条件的贴子
     */
    @Override
    public List<Post> searchPostByPage(int postBarId, String search, int page, int num, String sortClass, String sortWay) {
        List<Post> posts = JdbcUtil.query("select * from t_post where post_bar_id = ? and post_delete = 0 and concat(post_name, post_content) like ? order by "+ sortClass + " " + sortWay +"  limit " + (page-1)*num + "," + num, Post.class, postBarId, "%"+search+"%");
        return posts.size() == 0 ? null : posts;
    }

    @Override
    public int getAllSearchForNumber(int postBarId, String search) {
        return JdbcUtil.query("select post_id from t_post where post_bar_id = ? and post_delete = 0 and concat(post_name, post_content) like ? ", Post.class, postBarId, "%"+search+"%").size();
    }

    @Override
    public int getAllDeletePostForNumber(int postBarId) {
        return JdbcUtil.query("select post_id from t_post where post_bar_id = ? and post_delete = 1", Post.class, postBarId).size();
    }

    @Override
    public int createPost(Post post) {
        return JdbcUtil.insert("t_post", post);
    }

    @Override
    public boolean updatePost(Post post) {
        return JdbcUtil.update("t_post", "post_id = " + post.getPostId(), post);
    }
}
